--
--	CLIENT CORE
--
SCREEN_WIDTH, SCREEN_HEIGHT = guiGetScreenSize()

local function resourceStart()
	return
end
addEventHandler("onClientResourceStart", resourceRoot, resourceStart)

local function resourceStop()
	return
end
addEventHandler("onClientResourceStop", resourceRoot, resourceStop)

-- This function creates the handling editor.
function createEditor()
	if getElementByID("handlingEditor") then
		destroyEditor()
	end
	
	local localVehicle = getPedOccupiedVehicle(localPlayer)
	if (not localVehicle) or (getVehicleController(localVehicle) ~= localPlayer) then
		return
	end
			
	local mainWindow = guiCreateWindow(10, (SCREEN_HEIGHT/2)-250, 250, 500, "Handling Editor", false)
	guiWindowSetMovable(mainWindow, false)
	guiWindowSetSizable(mainWindow, false)
	
	guiNode = createElement("guiNode", "handlingEditor")
	setElementData(guiNode, "guiElements", {mainWindow}, false)
	
	if not isCursorShowing() then
		setElementData(guiNode, "hideCursor", true, false)
		showCursor(true)
	end
	
	addEventHandler("onClientRender", root, performEditorChecks)
end

-- This function destroys the editor.
function destroyEditor()
	local guiNode = getElementByID("handlingEditor")
	if not guiNode then
		return
	end
	
	local guiElements = getElementData(guiNode, "guiElements")
	for _, guiElement in ipairs(guiElements) do
		if isElement(guiElement) then
			destroyElement(guiElement)
		end
	end
	
	local hideCursor = getElementData(guiNode, "hideCursor", false)
	if hideCursor then	
		showCursor(false)
	end
	
	removeEventHandler("onClientRender", root, performEditorChecks)
	destroyElement(guiNode)
end

-- This function ensures the editor is only shown if the player is driving a vehicle.
function performEditorChecks()
	if not getElementByID("handlingEditor") then
		removeEventHandler("onClientRender", root, performEditorChecks)
		return
	end
	
	local localVehicle = getPedOccupiedVehicle(localPlayer)
	if localVehicle then
		if getVehicleController(localVehicle) == localPlayer then
			return
		else
			destroyEditor()
		end
	else
		destroyEditor()
	end
end

-- This function toggles the handling editor when the /handlingEditor command is used or the bound key is pressed.
local function toggleEditor()
	if getElementByID("handlingEditor") then
		destroyEditor()
	else
		createEditor()
	end
end
bindKey(getKeyBoundToCommand("handlingEditor") or "b", "down", toggleEditor)